from model import db
import datetime
from werkzeug.security import generate_password_hash
from sqlalchemy.dialects.mysql import LONGTEXT


class UserManager(db.Model):
    __tablename__ = "user"  # 映射的数据表，不写默认是类名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    password = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(128), nullable=False)
    phone = db.Column(db.String(24), nullable=False)
    avatar = db.Column(db.String(128), nullable=True)
    gender = db.Column(db.String(128), nullable=True)
    addr = db.Column(db.String(128), nullable=True)
    introduction = db.Column(LONGTEXT)
    birthday = db.Column(db.DateTime, nullable=True)
    followee_count = db.Column(db.Integer)
    follower_count = db.Column(db.Integer)
    CreateAt = db.Column(db.DateTime, default=datetime.datetime.now())

    def keys(self):
        return ("id", 'username', 'password', 'email', 'phone', 'gender', 'addr', 'introduction', 'birthday',
                'followee_count', 'follower_count', 'CreateAt')

    def __getitem__(self, item):
        return getattr(self, item)

    @property  # -----> password.setter，把password函数包装成属性
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod
    def create_user(cls, username, password, email, phone):
        # 实例化一个对象，即添加一行记录
        user = cls()
        user.username = username
        user.password = password
        user.email = email
        user.phone = phone
        db.session.add(user)
        db.session.commit()


# relationship 关系映射
# 一对一，一对多，多对多
# API授权表的模型
# 多对多的关系
# 存放映射关系的中间表，直接db.Table创建，分别外键到api_token.id和api_permission.id
app_permission = db.Table("app_permission",
                          db.Column("api_id", db.ForeignKey("api_token.id")),
                          db.Column("permission_id", db.ForeignKey("api_permission.id"))
                          )


# api_token表
# 存放的是授权密钥，以及授权id（即用户名密码的）
class ApiToken(db.Model):
    __tablename__ = "api_token"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appid = db.Column(db.String(128), nullable=False)
    secretkey = db.Column(db.String(128), nullable=False)
    # 通过中间表去创建多对多的关系
    manage = db.relationship("ApiPermission", secondary=app_permission, backref="token")


# 存放的是授权的url
class ApiPermission(db.Model):
    __tablename__ = "api_permission"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(128), nullable=False)
    method_type = db.Column(db.String(128), nullable=False)
